package com.study.spmongodb.book.wwj.char04;

import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/24 20:53
 */
public class Task implements Runnable {
    private final Object MUTEX = new Object();

    @Override
    public void run() {
        synchronized (MUTEX) {
            System.out.println(Thread.currentThread().getName() + " start");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " end");

        }
    }

    /**
     * 虽然构造了5个线程，同时也构造了5个Runnable实例，Runable作为逻辑执行单元传递给Thread，然后发现
     * synchronized根本互斥不了与之对应的作用域，线程之间进行monitor 的争抢只能发生在于monitor关联的同一个引用上，
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            final Task task = new Task();
            new Thread(task).start();
        }
        TimeUnit.MINUTES.sleep(1);
    }
}
